package com.supermarket.manage.business.instock.controller;

import com.supermarket.manage.business.instock.service.InstockBusinessService;
import com.supermarket.manage.common.constant.ExportConstant;
import com.supermarket.manage.common.constant.StockConstant;
import com.supermarket.manage.common.dto.PageBean;
import com.supermarket.manage.common.dto.ResponseResult;
import com.supermarket.manage.common.dto.stock.request.InstockPageParams;
import com.supermarket.manage.common.dto.stock.response.InstockDto;
import com.supermarket.manage.common.pojo.Instock;
import com.supermarket.manage.common.utils.POIUtil;
import com.supermarket.manage.common.utils.TimeUtil;
import com.supermarket.manage.common.validation.CheckGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-03-14 20:08
 **/
@RestController
@RequestMapping("/instock/purchase")
@Api(value = "PurchaseInstockController", tags = "采购入库单管理接口")
public class PurchaseInstockController {

    @Resource
    private InstockBusinessService instockBusinessService;

    @PreAuthorize("hasAnyAuthority('/','/instock/purchase/get')")
    @PostMapping("/getPurInstockPageList")
    @ApiOperation(value = "条件分页查询采购入库单", notes = "必传参数：page，size，buyerId，（其他条件为搜索条件）")
    public ResponseResult<PageBean<Instock>> getPurInstockPageList(@Validated({CheckGroup.Page.class})
                                                                   @RequestBody InstockPageParams params) {
        params.setType(StockConstant.SALE);
        return instockBusinessService.getInstockPageList(params);
    }

    @PreAuthorize("hasAnyAuthority('/','/instock/purchase/get')")
    @GetMapping("/export")
    @ApiOperation(value = "导出采购入库单", notes = "必传参数：buyerId（搜索条件页面上已输入的搜索条件）")
    public void export(@Validated({CheckGroup.Get.class}) InstockPageParams params, HttpServletResponse response) throws IOException {
        params.setType(StockConstant.SALE);
        List<Map<String, Object>> data = instockBusinessService.getInstockExportMap(params);

        String fileName = ExportConstant.PURCHASE_SHEETNAME + TimeUtil.getNow("yyyyMMdd");
        SXSSFWorkbook export = POIUtil.export(fileName, data, ExportConstant.PURCHASE_HEADERSNAME, ExportConstant.PURCHASE_KEYS);

        POIUtil.writeTo(fileName, export, response);
    }

    @PreAuthorize("hasAnyAuthority('/','/instock/purchase/get')")
    @GetMapping("/getById/{id}")
    @ApiOperation(value = "根据id获取入库单详情", notes = "根据id获取入库单详情")
    public ResponseResult<InstockDto> getInstockById(@NotBlank(message = "单据id不能为空")
                                                     @PathVariable String id) {
        return instockBusinessService.getInstockById(id);
    }

    @PreAuthorize("hasAnyAuthority('/','/instock/purchase/manage')")
    @GetMapping("/doneById/{id}")
    @ApiOperation(value = "根据id完成采购入库单据", notes = "根据id完成采购入库单据")
    public ResponseResult<Void> doneInstockById(@NotBlank(message = "单据id不能为空")
                                                @PathVariable String id) {
        return instockBusinessService.doneInstockById(id);
    }

    @PreAuthorize("hasAnyAuthority('/','/instock/purchase/manage')")
    @GetMapping("/deleteById/{id}")
    @ApiOperation(value = "根据id删除入库单据", notes = "根据id删除入库单据")
    public ResponseResult<Void> deleteInstockById(@NotBlank(message = "单据id不能为空")
                                                  @PathVariable String id) {
        return instockBusinessService.deleteInstockById(id);
    }

    @PreAuthorize("hasAnyAuthority('/','/instock/purchase/manage')")
    @PostMapping("/save")
    @ApiOperation(value = "保存采购入库单据", notes = "必传参数：sid，operator（当前登录用户的id），totalPrice，actuallyPrice，buyerId，商品数组。（入库单id在新增时不传，更新时传）" +
            "商品数组中每个商品的必要参数有pid，pnumber，subtotal（小计=商品数量*商品成本价）")
    public ResponseResult<Void> saveInstock(@Validated
                                            @RequestBody Instock instock) {
        return instockBusinessService.saveInstock(StockConstant.SALE, instock);
    }

    @PreAuthorize("hasAnyAuthority('/','/instock/purchase/manage')")
    @PostMapping("/done")
    @ApiOperation(value = "完成采购入库单据", notes = "必传参数：sid，operator（当前登录用户的id），totalPrice，actuallyPrice，buyerId。（入库单id在新增时不传，更新时传）" +
            "商品数组中每个商品的必要参数有pid，pnumber，subtotal（小计=商品数量*商品成本价）")
    public ResponseResult<Void> doneInstock(@Validated
                                            @RequestBody Instock instock) {
        return instockBusinessService.doneInstock(StockConstant.SALE, instock);
    }
}
